import { createRouter, createWebHistory } from 'vue-router'
import LoginView from "@/views/LoginView.vue";
import RegisterView from "@/views/RegisterView.vue";
import IndexView from "@/views/IndexView.vue";
import CartView from "@/views/CartView.vue";
import OrderView from "@/views/OrderView.vue";
import GoodsDetailView from "@/views/GoodsDetailView.vue";
import SecKillView from "@/views/SecKillView.vue";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    { path: '/', redirect: '/index'},
    { path: '/login', name: 'Login', component: LoginView},
    { path: '/register', name: 'Register', component: RegisterView},
    { path: '/index', name: 'Index',component: IndexView},
    { path: '/cart', name: 'Cart',component: CartView, meta: { requiresAuth: true }},
    { path: '/order', name: 'Order', component: OrderView, meta: { requiresAuth: true }},
    { path: '/goodsDetail/:gid', name: 'GoodsDetail', component: GoodsDetailView},
    { path: '/seckill', name: 'Seckill', component: SecKillView},
  ]
})

router.beforeEach((to, from, next) => {
  // 从 localStorage 中获取存储的 token
  const token = localStorage.getItem('token');

  // 检查即将跳转的路由是否需要身份验证
  if (to.matched.some(record => record.meta.requiresAuth) && !token) {
    // 如果需要身份验证且用户未登录，弹出提示框并重定向到登录页面
    alert('请先登录');
    next({ name: 'Login' });
  } else {
    // 如果不需要身份验证或用户已登录，继续当前导航
    next();
  }
});

export default router
